//
//  MyPromise.m
//  PromiseText
//
//  Created by mac123 on 2019/2/19.
//  Copyright © 2019年 wjh. All rights reserved.
//

#import "MyPromise.h"

@interface MyPromise ()
@property (nonatomic , strong) FirsBlock firstBlock;
@property (nonatomic , strong) CatchErrBlock errorBlock;
@property (nonatomic , strong) NSMutableArray *adapterBlocks;
@end
@implementation MyPromise

-(instancetype)init {
    if (self == [super init]) {
        self.adapterBlocks = [[NSMutableArray alloc] init];
    }
    return self;
}

+(MyPromise *)first:(FirsBlock)block {
    MyPromise *promise = [[MyPromise alloc] init];
    promise.firstBlock = block;
    return promise;
}

-(MyPromise * _Nonnull (^)(Adapter _Nonnull))then {
    __weak typeof(self) weakSelf = self;
    return ^(Adapter adapter){
        if(adapter) [weakSelf.adapterBlocks addObject:adapter];
        return weakSelf;
    };
}

-(MyPromise * _Nonnull (^)(CatchErrBlock _Nonnull))catchError {
    __weak typeof(self) weakSelf = self;
    return ^(CatchErrBlock errBlock){
        if(errBlock) weakSelf.errorBlock = errBlock;
        return weakSelf;
    };
}

-(void)start {
    FirsBlock block = self.firstBlock;
    PassBlock pass = ^(id data){
        /** 为保持MyPromise生命周期在异步环境下延长，此处使用强引用 */
        if ([data isKindOfClass:[NSError class]]) {
            [self excuteErrorBlock:data];
        }else{
            [self excuteThenBlock:data];
        }
    };
    block(pass);
}

-(void)excuteThenBlock:(id)data {
    Adapter adapter = self.adapterBlocks.firstObject;
    PassBlock pass = ^(id newData){
        /** 为保持MyPromise生命周期在异步环境下延长，此处使用强引用 */
        if ([newData isKindOfClass:[NSError class]]) {
            [self excuteErrorBlock:newData];
        }else{
            [self excuteThenBlock:newData];
        }
    };
    if(adapter) {
        [self.adapterBlocks removeObject:adapter];
        adapter(data ,pass);
    }
}

-(void)excuteErrorBlock:(NSError *)error {
    CatchErrBlock errBlock = self.errorBlock;
    if (errBlock) {
        errBlock(error);
    }
}


@end
